﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using System.Web.Security;

namespace DataAccess
{
    public class EnterpriseUserDataAccess
    {
        public void CreateUser(EnterpriseUser user)
        {
            Database db = DatabaseFactory.CreateDatabase();

            string sql = "insert into EnterpriseUser values(@Id,@Password,@CompanyType,@CompanyName" +
                        ",@RegisterLocation,@BusinessLocation,@Industry,@Business,@Email,@FixPhone,@Fax,@Contact1,@Contact2,@Contact3,@ReceiveMsg)";

            DbCommand command = db.GetSqlStringCommand(sql);

            db.AddInParameter(command, "@Id", DbType.String, user.Id);
            db.AddInParameter(command, "@Password", DbType.String,
                              FormsAuthentication.HashPasswordForStoringInConfigFile(user.Password, "SHA1"));
            db.AddInParameter(command, "@CompanyType", DbType.String, user.CompanyType);
            db.AddInParameter(command, "@CompanyName", DbType.String, user.CompanyName);
            db.AddInParameter(command, "@RegisterLocation", DbType.String, user.RegisterLocation);
            db.AddInParameter(command, "@BusinessLocation", DbType.String, user.BusinessLocation);
            db.AddInParameter(command, "@Industry", DbType.String, user.Industry);
            db.AddInParameter(command, "@Business", DbType.String, user.Business);
            db.AddInParameter(command, "@Email", DbType.String, user.Email);
            db.AddInParameter(command, "@FixPhone", DbType.String, user.FixPhone);
            db.AddInParameter(command, "@Fax", DbType.String, user.Fax);
            db.AddInParameter(command, "@Contact1", DbType.String, user.Contact1);
            db.AddInParameter(command, "@Contact2", DbType.String, user.Contact2);
            db.AddInParameter(command, "@Contact3", DbType.String, user.Contact3);
            db.AddInParameter(command, "@ReceiveMsg", DbType.Boolean, user.ReceiveMsg);

            db.ExecuteNonQuery(command);
        }
        public bool Authenticate(string userName, string userPassword)
        {
            Database db = DatabaseFactory.CreateDatabase();

            string sql = "select count(*) from Users where Id=@Id and Password=@Password";

            DbCommand cmd = db.GetSqlStringCommand(sql);

            db.AddInParameter(cmd, "@Id", DbType.String, userName);
            db.AddInParameter(cmd, "@Password", DbType.String,
                            FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword, "SHA1"));

            if (db.ExecuteScalar(cmd).ToString() == "1")
                return true;
            return false;

        }
    }
}
